// 初始化地址数据 | Initialize address data
/**
 * 从localStorage加载已有地址数据，若不存在则初始化为空数组
 * Load existing addresses from localStorage, initialize as empty array if not exist
 */
let addresses = JSON.parse(localStorage.getItem('addresses')) || [];

// 初始化页面时渲染地址
window.addEventListener('DOMContentLoaded', () => {
  updateAddressCount();
  renderAddressList();
});

// 打开模态框
function openAddressModal() {
  document.getElementById('addressModal').style.display = 'block';
  resetProvinceSelection();
}

// 关闭模态框
function closeAddressModal() {
  document.getElementById('addressModal').style.display = 'none';
}

// 保存地址 | Save address
/**
 * 收集表单数据并执行以下操作：
 * 1. 表单验证 2. 维护最多5个地址 3. 持久化存储 4. 更新UI
 * 
 * Collect form data and perform:
 * 1. Form validation 2. Maintain max 5 addresses 3. Persist storage 4. Update UI
 */
function saveAddress() {
  const formData = {
    receiver: document.getElementById('receiver').value,
    province: document.getElementById('province').value,
    city: document.getElementById('city').value,
    district: document.getElementById('district').value,
    detail: document.getElementById('detail').value,
    mobile: document.getElementById('mobile').value,
    alias: document.getElementById('alias').value,
    email: document.getElementById('email').value
  };

  if (!validateForm(formData)) return;

  addresses.push(formData);

  localStorage.setItem('addresses', JSON.stringify(addresses));
  closeAddressModal();
  renderAddressList();
  updateAddressCount();
}

// 表单验证 | Form validation
/**
 * 验证必填字段：收货人、省份、城市、区县、详细地址、手机号
 * 任意字段缺失时弹出中文提示
 * 
 * Validate required fields: receiver, province, city, district, detail, mobile
 * Show Chinese alert when any required field is missing
 */
function validateForm(data) {
  if (addresses.length >= 5) {
    alert('收货地址数量已达上限（最多5个）');
    return false;
  }
  
  const requiredFields = ['receiver', 'province', 'city', 'district', 'detail', 'mobile'];
  return requiredFields.every(field => {
    if (!data[field]) {
      alert(`请填写${getFieldName(field)}`);
      return false;
    }
    return true;
  });
}

// 获取字段中文名
function getFieldName(field) {
  const names = {
    receiver: '收货人',
    province: '省份',
    city: '城市',
    district: '区县',
    detail: '详细地址',
    mobile: '手机号码'
  };
  return names[field];
}

// 更新地址数量显示
function updateAddressCount() {
  document.getElementById('addressCount').textContent = 
    `您已创建 ${addresses.length} 个收货地址，最多创建5个${addresses.length >=5 ? '（已达上限）' : ''}`;
}

// 渲染地址列表 | Render address list
/**
 * 使用模板字符串生成地址卡片，包含以下功能：
 * 1. 显示地址序号和别名 2. 组合完整地址 3. 展示联系方式
 * 
 * Generate address cards with template string, features:
 * 1. Display index & alias 2. Combine full address 3. Show contact info
 */
function renderAddressList() {
  const container = document.getElementById('addressList');
  container.innerHTML = addresses.map((addr, index) => `
    <div class="address-item">
      <h4>地址 ${index + 1}${addr.alias ? ' (' + addr.alias + ')' : ''}</h4>
      <p>${addr.province} ${addr.city} ${addr.district}</p>
      <p>${addr.detail}</p>
      <p>收货人：${addr.receiver}</p>
      <p>联系方式：${addr.mobile}${addr.email ? ' / ' + addr.email : ''}</p>
    </div>
  `).join('');
}



// 初始化省份选项
function resetProvinceSelection() {
  const provinceSelect = document.getElementById('province');
  provinceSelect.innerHTML = Object.keys(regions)
    .map(p => `<option value="${p}">${p}</option>`);
  updateCityOptions();
}

// 更新城市选项
function updateCityOptions() {
  const province = document.getElementById('province').value;
  const citySelect = document.getElementById('city');
  const cities = Object.keys(regions[province]);
  citySelect.innerHTML = cities.map(c => `<option value="${c}">${c}</option>`);
  updateDistrictOptions();
}

// 更新区县选项
function updateDistrictOptions() {
  const province = document.getElementById('province').value;
  const city = document.getElementById('city').value;
  const districtSelect = document.getElementById('district');
  const districts = regions[province][city];
  districtSelect.innerHTML = districts.map(d => `<option value="${d}">${d}</option>`);
}
1
